package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"mime/multipart"
	"nearby/biz/common"
	"nearby/biz/manager/ali_oss"
	"nearby/biz/model"
)

type UploadImagesService struct {
}

func (ss *UploadImagesService) checkParam(ctx context.Context, files []*multipart.FileHeader) error {
	if len(files) > 9 {
		return errors.New("单次上传的图片数量超出限制")
	}
	for i := range files {
		file := files[i]
		if file.Size > common.ImageSizeLimit {
			return errors.New(fmt.Sprintf("第%d张图片超出5MB限制", i+1))
		}
		if !ali_oss.IsImage(file.Filename) {
			return errors.New(fmt.Sprintf("第%d张文件的图片类型未知", i+1))
		}
	}
	return nil
}

func (ss *UploadImagesService) Execute(c *gin.Context, req *model.UploadImagesRequest) (*model.UploadImagesResponse, error) {
	form, err := c.MultipartForm()
	if err != nil {
		log.Printf("ctx: %+v; c.MultipartForm() fail, err: %+v", c, err)
		return nil, common.NewBizErr(common.BizErrCode, fmt.Sprintf("解析文件的时候有问题, 报错: c.MultipartForm(), err: %+v", err), err)
	}
	files := form.File["files"]
	if err := ss.checkParam(c, files); err != nil {
		return nil, common.NewBizErr(common.BizErrCode, err.Error(), err)
	}
	var uploader *UploadImageService
	urls := make([]string, len(files))
	for i := range files {
		file := files[i]
		key := uploader.GenerateObjKey(c, file.Filename)
		if err := uploader.UploadImage(c, key, file); err != nil {
			return nil, common.NewBizErr(common.BizErrCode, err.Error(), err)
		}
		urls[i] = ali_oss.GetUrl(key)
	}

	return &model.UploadImagesResponse{
		Meta:      common.MetaOk,
		ImageURLs: urls,
	}, nil
}
